import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/alert_business/mine/vip_level_dialog.dart';
import 'package:tiktokadult/hj_page/user_center_page/switch_background_entity.dart';
import 'package:tiktokadult/hj_utils/api_service/mine_service.dart';
import 'package:tiktokadult/hj_utils/global.dart';

import '../../../hj_utils/video_utils.dart';
import '../../../tools_base/file_upload/file_upload_tool.dart';
import '../../../tools_base/global_store/store.dart';
import '../../../tools_base/loading/loading_alert_widget.dart';

class SelectPortraitLogic extends GetxController {
  List<SwitchAvatarDataList> dataModel = [];
  int? selectIndex;

  @override
  void onInit() {
    super.onInit();
    fetchPortrait();
  }

  void fetchPortrait() async {
    final retModel = await MineService.getBloggerAvatarAndBg('avatar');
    dataModel.addAll(retModel?.avatarList ?? []);
    update();
  }

  void select(int index) {
    selectIndex = index;
    update();
  }

  //上传头像
  void submit(BuildContext context, String url, bool showLoading, {bool isDefaultSource = false}) async {
    if (url.isEmpty) {
      showToast("请先选择头像");
      return;
    }

    if (showLoading) LoadingAlertWidget.show();
    final userInfo = await globalStore.updateUserInfo(map: {
      'portrait': url,
      'isDefaultSource': isDefaultSource,
    });
    if (showLoading) LoadingAlertWidget.cancel();
    if (null != userInfo) {
      showToast("修改成功");
      Get.back(result: true);
    } else {
      showToast("操作失败");
    }
  }

  void selectImage(BuildContext context) async {
    //1.判断头像审核状态
    if ((globalStore.meInfo?.urrPortraitStatus ?? 0) == 1) {
      showToast('头像审核中~');
      return;
    }
    //2.判断vip
    if (!globalStore.isRechargeVIP()) {
      showVipLevelDialog('您还不是VIP，无法上传头像');
      return;
    }
    List<String> list = await VideoUtils.pickImg(1);
    if (list.isNotEmpty && list.length > 0) {
      LoadingAlertWidget.show();
      try {
        LoadingAlertWidget.showExchangeTitle("正在上传图片...");
        var uploadImgArr = await FileUpLoadTool().uploadImageList(list, proCallback: (tIndex, tAll, proCount, totalCount) {
          LoadingAlertWidget.showExchangeTitle("正在上传图片${(100 * (proCount / totalCount / tAll + tIndex / tAll)).toStringAsFixed(1)}%");
        });
        List<String> imageArr = [];
        if (uploadImgArr?.isNotEmpty == true) {
          imageArr = uploadImgArr!.map((e) => e.coverImg ?? "").toList();
        }
        LoadingAlertWidget.showExchangeTitle("正在更新数据...");

        submit(context, imageArr.first, true);
      } on DioException catch (e) {
        showToast(e.message ?? '');
      } catch (e) {
        showToast(e.toString());
      } finally {
        LoadingAlertWidget.cancel();
      }
    }
  }
}
